import redirect from "./redirect";
import { getCookie,removeCookie } from "./session";
import Router from 'next/router'
import nextCookie from 'next-cookies'

export const getJwt = ctx => {
    return getCookie("token", ctx.req);
};

export const signOut = (ctx = {}) => {
    if (process.browser) {
        removeCookie("token");
        // window.localStorage.clear()
        // redirect("/login", ctx);
    }
};

export function withAuthSync (WrappedComponent) {
    return class extends Component {
        constructor (props) {
            super(props)
    
            this.syncLogout = this.syncLogout.bind(this)
        }
        componentDidMount () {
            window.addEventListener('storage', this.syncLogout)
        }
        componentWillUnmount () {
            window.removeEventListener('storage', this.syncLogout)
            window.localStorage.removeItem('logout')
        }
        syncLogout (event) {
            if (event.key === 'logout') {
                console.log('logged out from storage!')
                Router.push('/login')
            }
        }
        render () {
            return <WrappedComponent {...this.props} />
        }
    }
}
  
export default ctx => {
    const { token } = nextCookie(ctx)
    if (ctx.req && !token) {
        ctx.res.writeHead(302, { Location: '/login' })
        ctx.res.end()
        return
    }
    if (!token) {
        Router.push('/login')
    }
    return token
}